<template>
  <div>
    <el-dialog width="70%" :visible.sync="formShow" @close="handleClickDeal('cancel')" v-dialog-drag :modal-append-to-body="false" :close-on-click-modal="false">
      <span slot="title">
        <i class="iconfont icon-rizhi"></i>
        <span>{{title}}</span>
      </span>
      <el-tabs v-model="activeName">
        <el-form :model="formBaseData" ref="formBaseData" :rules="formBaseRules" class="measurepaycompensation_detail_form">
          <el-row>
            <el-col :span="12">
              <el-form-item class="" label="分解月份" prop="decompositionMonth" :label-width="formlabelWidth">
                <el-input size="small" v-model="formBaseData.decompositionMonth" placeholder="" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="" label="周数" prop="weekCount" :label-width="formlabelWidth">
                <el-input style="width: 80%;" size="small" type="number" v-model="formBaseData.weekCount" placeholder="" :disabled="detailType === 'check'|| weekCountEdit === false" @blur='updateDetail'></el-input>
                <el-button v-if="weekCountEdit==false" type="primary" @click="weekCountEdit=!weekCountEdit">重置</el-button>
                <el-button v-else type="primary" @click="weekCountEdit=!weekCountEdit">确定</el-button>
              </el-form-item>
            </el-col>
          </el-row>

          <!--
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="所属半月"
                prop="halfMonth"
                :label-width="formlabelWidth"
              >
                <el-select
                  class="select"
                  value-key="id"
                  v-model="formBaseData.halfMonth"
                  placeholder="选择所属半月"
                  style="width: 100%"
                  :disabled="detailType === 'check' || detailType === 'approve' "
                >
                  <el-option
                    v-for="item in halfMonthTree"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

          </el-row>
-->

          <el-row>
            <el-col :span="24">
              <el-form-item prop="remark" label="备注" :label-width="formlabelWidth">
                <el-input class="fill" type="textarea" :autosize="{ minRows: 4, maxRows: 6}" placeholder="" v-model="formBaseData.remark" :disabled="detailType === 'check'|| detailType === 'approve' ">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table class="project-management-info1" :border="true" height="610px" :row-class-name="tableRowStyleName" :cell-class-name="tableCellStyleName" :header-cell-class-name="tableHeaderCellStyleName" :stripe="true" ref="multipleTable" :data="listOne" tooltip-effect="dark" style="
              width: 100%;
              font-family: PingFangSC-Regular;
              font-size: 14px;
            " @cell-click="cellClick">
          <el-table-column show-overflow-tooltip prop="xh" align="center" label="序号" width="100">
          </el-table-column>

          <el-table-column show-overflow-tooltip label="周数" width="400" prop="weekName">
          </el-table-column>

          <el-table-column show-overflow-tooltip label="起止日期" prop="startDate">
            <template slot-scope="scope">
              <div style="text-align: center">
                <el-date-picker v-model="scope.row.startEndDate" type="daterange" :default-value="new Date(defaultMonth)" :disabled="detailType === 'check' || detailType === 'approve'" unlink-panels :picker-options="pickerOptions0" v-on:change="setPlanDate(scope.row)" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="​起始日期" end-placeholder="结束日期">
                </el-date-picker>
              </div>
            </template>
          </el-table-column>

          <!-- <el-table-column show-overflow-tooltip label="所属半月" prop="startDate">
            <template slot-scope="scope">
              <el-select class="select" value-key="id" v-model="scope.row.halfMonth" placeholder="选择所属半月" style="width: 100%" :disabled="detailType === 'check' || detailType === 'approve' ">
                <el-option v-for="item in halfMonthTree" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </template>
          </el-table-column> -->

        </el-table>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <!--api操作按钮 除去上报-->
        <!--新建和编辑的暂存上报-->
        <template v-if="detailType === 'build' || detailType === 'edit'">
          <el-button size="small" type="primary" :loading="isLoading" @click="handleClickDeal('submit', {flag: 1})">
            <i class="iconfont icon-icon_save"></i> 确 定</el-button>
        </template>
        <el-button size="small" @click="handleClickDeal('cancel')"><i class="iconfont icon-icon_cancel"></i> 取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  tableRowStyleGol,
  tableCellStyleGol,
  tableHeaderCellStyleGol,
} from '@/utils/publicFun'
import projectSectionInfo from "@/api/buss/common";
import sectionInfo from "@/api/buss/sectionInfo";
import msgUtil from "@/utils/msgUtil";
import weeksDefinition from "@/api/buss/weeksDefinition";

export default {
  name: "weeksDefinition-detail",
  props: {
    postDetail: {
      type: Object,
      default: {
        show: false,
        type: 'build',
        params: {}
      }
    }
  },
  watch: {
    postDetail(value) {
      console.log("value=", value)
      // 显示详情弹窗
      this.formShow = value.show
      // 初始化窗口参数
      this.activeName = 'first'
      // 详情类型
      this.detailType = value.type
      if (this.detailType == 'build') {
        this.title = '新增周数定义'
      } else if (this.detailType == 'check') {
        this.title = '查看周数定义'
      } else if (this.detailType == 'edit') {
        this.title = '编辑周数定义'
      } else if (this.detailType == 'approve') {
        this.title = '周数定义审核'
      } else {
        this.title = ''
      }
      this.formBaseData.decompositionMonth = value.params.month;
      this.formBaseData.year = value.params.searchYear;
      this.formBaseData.month = value.params.searchMonth;
      this.searchYear = value.params.searchYear;
      this.searchMonth = value.params.searchMonth;
      this.checkCanEdit();
      this.getDetail()
    }
  },
  data() {
    return {
      pickerOptions0: this.disabledFun(),
      canEdit: false,
      searchYear: '',
      searchMonth: '',
      weekCountEdit: false,
      listOne: [],
      defaultMonth: '',
      tableRowStyleName: tableRowStyleGol,
      tableCellStyleName: tableCellStyleGol,
      tableHeaderCellStyleName: tableHeaderCellStyleGol,
      fileList: [],
      halfMonthTree: [
        { id: '1', name: '上半月' },
        { id: '2', name: '下半月' },
      ],// 所属半月
      companyTree: [], // 公司下拉

      projectTree: [], // 项目下拉
      sectionTree: [], // 标段下拉
      isLoading: false,
      actionType: '查看',
      title: '周数定义',
      isYz: false,//上报人公司类型 是否是业主
      //存放图片的数组
      fileListArray: [],
      detailType: 'build', // 详情类型 build新建 check不可编辑查看 edit编辑
      detailId: '', // 当前详情的id
      activeName: 'first', //
      detailActions: [], // 当前详情的操作项
      formShow: false, // 表单展示
      radioValue: '',//单选按钮选中的值
      formlabelWidth: '140px', // 表单左侧标题宽度
      selectList: {
        file: [], // 文件
        approver: [], // 审批人
        structureType: [], // 结构类型
      },
      fileSystem: {
        'one': {
          sys: 'buss',
          module: 'weeksDefinition',
          part: 'one',
          compoName: 'fileOne'
        }
      }, // 文件系统的参数
      // 所有下拉框列表的集合
      // 表单基本信息内容
      formBaseData: {
        id: '',
        decompositionMonth: '',
        halfMonth: '',
        weekCount: '',
        remark: '',
      },

      // 表单基本信息验证
      formBaseRules: {
        decompositionMonth: [
          { required: true, message: '请输入' + '分解月份', trigger: 'blur' },
        ],
        weekCount: [
          { required: true, message: '请输入' + '周数', trigger: 'blur' },
        ],
      },
      chooseRow: '',
    }
  },
  created() {
  },
  methods: {
    cellClick(row, column, cell, event) {
      this.chooseRow = row
    },
    disabledFun() {
      const self = this
      return {
        disabledDate(time) {
          for (let i in self.listOne) {
            let item = self.listOne[i]
            if (item.weekName !== self.chooseRow.weekName) {
              if (item.startDate && item.endDate) {
                if ((time.getTime() >= (new Date(item.startDate).getTime() - (8 * 3600 * 1000))) && (time.getTime() <= new Date(item.endDate).getTime())) {
                  return true
                }
              }
            }
          }
        }
      }
    },
    setPlanDate(row) {
      if (row.startEndDate) {
        this.$set(row, 'startDate', row.startEndDate[0]);
        this.$set(row, 'endDate', row.startEndDate[1]);
      } else {
        this.$set(row, 'startDate', '');
        this.$set(row, 'endDate', '');
        this.$set(this, 'defaultMonth', (this.formBaseData.decompositionMonth.replace('年', '-')).replace('月', ''))
      }
    },
    changeNumToHan(num) {
      var arr1 = new Array(
        "零",
        "一",
        "二",
        "三",
        "四",
        "五",
        "六",
        "七",
        "八",
        "九"
      );
      var arr2 = new Array(
        "",
        "十",
        "百",
        "千",
        "万",
        "十",
        "百",
        "千",
        "亿",
        "十",
        "百",
        "千",
        "万",
        "十",
        "百",
        "千",
        "亿"
      ); //可继续追加更高位转换值
      if (!num || isNaN(num)) {
        return "零";
      }
      var english = num.toString().split("");
      var result = "";
      for (var i = 0; i < english.length; i++) {
        var des_i = english.length - 1 - i; //倒序排列设值
        result = arr2[i] + result;
        var arr1_index = english[des_i];
        result = arr1[arr1_index] + result;
      }
      //将【零千、零百】换成【零】 【十零】换成【十】
      result = result.replace(/零(千|百|十)/g, "零").replace(/十零/g, "十");
      //合并中间多个零为一个零
      result = result.replace(/零+/g, "零");
      //将【零亿】换成【亿】【零万】换成【万】
      result = result.replace(/零亿/g, "亿").replace(/零万/g, "万");
      //将【亿万】换成【亿】
      result = result.replace(/亿万/g, "亿");
      //移除末尾的零
      result = result.replace(/零+$/, "");
      //将【零一十】换成【零十】
      //result = result.replace(/零一十/g, '零十');//貌似正规读法是零一十
      //将【一十】换成【十】
      result = result.replace(/^一十/g, "十");
      return result;
    },
    updateDetail() {
      if (this.formBaseData.weekCount > 10) {
        this.$messageWarning("周数不能大于10")
        this.formBaseData.weekCount = 0
        this.listOne = []
        return false
      }
      this.$set(this, 'defaultMonth', (this.formBaseData.decompositionMonth.replace('年', '-')).replace('月', ''))
      this.listOne = []
      for (let i = 0; i < this.formBaseData.weekCount; i++) {
        this.listOne.push({ xh: i + 1, weekName: '第' + this.changeNumToHan(i + 1) + '周', startEndDate: [] })
      }
    },
    changeSectionInfo() {
      sectionInfo.getCompanyBySecId(this.formBaseData.sectionId).then(res => {
        if (res.status === 1) {
          var data = res.data;
          this.formBaseData.constrCompanyName = data.buildUnit
          this.formBaseData.supervisorCompanyName = data.supervisorUnit
          this.formBaseData.constrCompany = data.buildUnitId
          this.formBaseData.supervisorCompany = data.supervisorUnitId
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取标段相关单位失败")
      })
    },
    // 获取详情请求 api

    // 校验是否可以修改
    checkCanEdit() {
      let postData = {
        year: this.searchYear,
        month: this.searchMonth
      }
      this.$httpPost(`/buss/progressschedulemonthly/checkCanEdit`, postData).then(res => {
        if (res.code === 200) {
          if (res.data == '2') {
            this.canEdit = true
          } else {
            this.canEdit = false
          }
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch((res) => {
        console.log(res)
      }).finally((response) => {
      })
    },
    getDetail() {
      let params = {
        pageNo: 0,
        pageSize: 200,
        pageSum: 0,
        year: this.searchYear,
        month: this.searchMonth
      }
      weeksDefinition.listPage(params).then(res => {
        if (res.code == 200) {
          if (res.data.content.length > 0) {
            let data = res.data.content[0]
            this.$set(this.formBaseData, 'weekCount', data.weekCount)
            this.$set(this.formBaseData, 'id', data.id)
            this.$set(this.formBaseData, 'remark', data.remark)
            this.$set(this.formBaseData, 'year', data.year)
            this.$set(this.formBaseData, 'month', data.month)
            data.weekDetailList.forEach(item => {
              this.listOne.push(JSON.parse(item))
            })
          }
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取详情信息失败")
      })
    },

    // 提交详情 提交1/暂存0 新建0/修改1
    submitDetail(type, callback, slient) {
      if (this.formBaseData.id == '') {
        let weekDetailList = []
        let flag = false
        this.listOne.forEach(item => {
          if (item.startEndDate.length == 2) {
            weekDetailList.push(JSON.stringify(item))
          } else {
            flag = true
          }
        })
        if (flag) {
          this.$messageWarning("起止日期不能为空！")
          return false
        }
        this.isLoading = true
        this.formBaseData.weekDetailList = weekDetailList
        weeksDefinition.submit(this.formBaseData).then(res => {
          if (res.code === 200) {
            this.formShow = false
            this.detailId = res.data.id
            if (callback) callback()
          } else {

            msgUtil.error2(res.data.message)
          }
        }).catch((res) => {
          console.log(res)
        }).finally((response) => {
          this.isLoading = false
        })
      } else {
        this.isLoading = true
        let weekDetailList = []
        let flag = false
        this.listOne.forEach(item => {
          if (item.startEndDate.length == 2) {
            weekDetailList.push(JSON.stringify(item))
          } else {
            flag = true
          }
        })
        if (flag) {
          this.$messageWarning("起止日期不能为空！")
          return false
        }
        this.formBaseData.weekDetailList = weekDetailList
        weeksDefinition.resubmit(this.formBaseData).then(res => {
          if (res.code === 200) {
            this.formShow = false
            this.detailId = res.data.id
            if (callback) callback()
          } else {
            msgUtil.error2(res.data.message)
          }
        }).catch((res) => {
          console.log(res)
        }).finally((response) => {
          this.isLoading = false
        })
      }
    },
    // 事件处理的api请求
    sealDealHttp(url, query, params, callback) {
      this.$httpPost(
        this.$store.state.httpHost.buss + url + query,
        params
      ).then(res => {
        if (res.data.status === 1) {
          if (callback) callback(res.data)
        } else {
          this.$messageError(res.data.message)
        }
      }).catch(res => {
        console.log(res)
      })
    },
    // 点击各个流程的按钮事件
    handleClickDeal(type, res) {
      console.log(type, res)
      switch (type) {
        // 取消，关闭窗口
        case 'cancel':
          // 重置表单验证
          this.$refs['formBaseData'].resetFields()
          // 清空表单内容
          this.formBaseData = {
            id: '',
            decompositionMonth: '',
            halfMonth: '',
            weekCount: '',
            remark: '',
          } // 表单基本信息内容
          this.listOne = []
          this.weekCountEdit = false
          // 关闭弹窗
          this.formShow = false
          break
        // 保存
        case 'submit':
          let flag = res.flag
          // 表单验证
          this.$refs['formBaseData'].validate((valid) => {
            if (!this.canEdit) {
              this.$messageWarning("周数在进度管理模块被引用，不允许修改")
              return
            }
            if (valid) {
              // 提交详情
              this.submitDetail(flag, () => {
                this.$emit('reloadList')
                this.$notify({
                  title: '周数定义保存成功',
                  type: 'success',
                  duration: 1500
                })
              }, true)
            }
          });
          break
        // 删除
        case 'delete':
          break
      }
    },
    saveFiles() {
      for (let k in this.fileSystem) {
        let fileProp = this.fileSystem[k]
        this.$refs[fileProp.compoName].saveAll(this.detailId)
      }
    },

    loadFiles() {
      this.$nextTick(() => {
        for (let k in this.fileSystem) {
          let fileProp = this.fileSystem[k]
          this.$refs[fileProp.compoName].init()
        }
      })
    },
  },
}
</script>

<style scoped lang="scss">
.el-select.half {
  width: 250px;
}
.el-select.fill {
  width: 800px;
}

.el-input .el-select {
  width: 130px;
}
.fee_add {
  color: #008fe0;
  border-color: #008fe0;
  float: right;
  margin-bottom: 10px;
}
</style>
